package com.hhh.sun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.sun.mapper.TbUserMapper;
import com.hhh.sun.pojo.entity.TbUser;
import com.hhh.sun.service.UserService;
import com.hhh.sun.vo.req.LoginReqVo;
import com.hhh.sun.vo.resp.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements UserService {
    /**
     * 用户登录功能
     * @param vo 用户登录请求封装类
     */
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        LambdaQueryWrapper<TbUser>wrapper= Wrappers.<TbUser>lambdaQuery().eq(TbUser::getUserName,vo.getUserName());
        TbUser user = baseMapper.selectOne(wrapper);
        //判断用户是否存在
        if(user==null){
            return R.error(ResponseCode.ACCOUNT_EXISTS_ERROR);
        }
        //比对密码是否相同
        if(!user.getPassword().equals(vo.getPassword())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //封装返回对象
        LoginRespVo loginRespVo = new LoginRespVo();
        BeanUtils.copyProperties(user,loginRespVo);
        return R.ok(loginRespVo);
    }
    /**
     * 分页查询所有用户
     */
    @Override
    public R<PageResult<TbUser,QueryUserVo>> findAllUser(Integer pageNum,Integer pageSize) {
        IPage<TbUser>page=new Page<>(pageNum,pageSize);
        baseMapper.selectPage(page,null);
        //封装响应结果
        List<QueryUserVo> list = page.getRecords().stream().map(tbUser -> {
            QueryUserVo vo = new QueryUserVo();
            BeanUtils.copyProperties(tbUser, vo);
            return vo;
        }).collect(Collectors.toList());
        PageResult<TbUser, QueryUserVo> result = new PageResult<>(page, list);
        return R.ok(result);
    }
}
